<template>
  <div class="plan-upload-container-padding">
    <el-form
      ref="ruleFormRef"
      style="max-width: 800px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="项目名称:" prop="projectName">
        <div class="flex">
          <el-input v-model="ruleForm.projectName" />
          <el-button type="primary" style="margin-left: 20px" @click="handleAi">
            AI智能查重
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="项目编号:" prop="projectCode">
        <el-input v-model="ruleForm.projectCode" />
      </el-form-item>
      <el-form-item label="项目级别:" prop="projectLevel">
        <el-select
          v-model="ruleForm.projectLevel"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in dictStore.getDictType('project_level')"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目类型:" prop="projectType">
        <el-cascader
          v-model="ruleForm.projectType"
          :options="projectTypes"
          :props="optionProps"
          placeholder="请选择"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="是否重点项目:" prop="keyProject">
        <el-select
          v-model="ruleForm.keyProject"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in dictStore.getDictType('yes_no')"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目负责人:" prop="headerId">
        <el-select
          v-model="ruleForm.headerId"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="item in users"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div style="margin-top: 40px">
      <TopicSelectModal ref="topicSelectRef" :type="3" />
    </div>
    <CommonFooterBar>
      <el-button
        type="primary"
        :loading="loading"
        @click="submitForm(ruleFormRef)"
      >
        确认提交
      </el-button>
    </CommonFooterBar>
  </div>
</template>

<script setup>
  import { useDictStore } from '@/store/modules/dict'
  import TopicSelectModal from '@/components/topicSelectModal'
  import {
    projectPlanGetProject,
    projectPlanUpdate,
  } from '@/api/project/approval/plan'
  import { getAllUser } from '@/api/system/user'
  import CommonFooterBar from '@/components/commonFooterBar'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'
  import { getDictTypeTree } from '@/api/system/dict/dict.data'

  const { closeTabNavigate } = useCloseTabNavigate()

  const $baseMessage = inject('$baseMessage')

  const dictStore = useDictStore()
  const route = useRoute()
  const router = useRouter()

  const users = ref([])
  const loading = ref(false)

  const ruleFormRef = ref()
  const ruleForm = reactive({})
  const rules = reactive({
    projectName: [
      {
        required: true,
        message: '请输入项目名称',
      },
    ],
    projectCode: [
      {
        required: true,
        message: '请输入项目编号',
      },
    ],
    projectLevel: [
      {
        required: true,
        message: '请选择项目级别',
        trigger: 'change',
      },
    ],
    projectType: [
      {
        required: true,
        message: '请选择项目类型',
        trigger: 'change',
      },
    ],
    keyProject: [
      {
        required: true,
        message: '请选择是否重点项目',
        trigger: 'change',
      },
    ],
    headerId: [
      {
        required: true,
        message: '请选择项目负责人',
        trigger: 'change',
      },
    ],
  })

  const topicSelectRef = ref()
  const projectTypes = ref([])
  const planId = ref('')

  const optionProps = {
    value: 'value',
    label: 'label',
    emitPath: false, //只传最后一级id
  }

  const handleAi = () => {
    if (!ruleForm.projectName) {
      return $baseMessage('请输入课题名称', 'error')
    }
    router.push(`/project/knowledge/ai?keywords=${ruleForm.projectName}`)
  }

  const getUserList = () => {
    getAllUser().then((res) => {
      if (res.code == 0 || res.code == 200) {
        users.value = res.data || []
      }
    })
  }

  const getProjectInfo = () => {
    projectPlanGetProject({ topicId: route.query.id }).then((res) => {
      if (res.code == 0 || res.code == 200) {
        const { projectInfo, topicInfos, projectPlanInfo } = res.data
        ruleForm.id = projectInfo?.id || ''
        ruleForm.projectName = projectInfo?.projectName || ''
        ruleForm.projectCode = projectInfo?.projectCode || ''
        ruleForm.projectLevel = projectInfo?.projectLevel || ''
        ruleForm.projectType = projectInfo?.projectType || ''
        ruleForm.keyProject = projectInfo?.keyProject || ''
        ruleForm.headerId = projectInfo?.headerId || ''
        topicSelectRef.value.tableData = topicInfos ? topicInfos : []
        planId.value = projectPlanInfo?.id || ''
      }
    })
  }

  //获取项目类型
  const getProjectTypes = () => {
    getDictTypeTree({ parentId: 158 }).then((res) => {
      if (res.code == 0 || res.code == 200) {
        projectTypes.value = res.data.children || []
      }
    })
  }

  //表单提交
  const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        const topicData = topicSelectRef.value
          .getTableData()
          .filter((item) => item.id)
        if (!topicData || !topicData.length) {
          return $baseMessage('请选择课题', 'error')
        }
        loading.value = true
        const params = {
          id: planId.value,
          projectInfo: {
            ...ruleForm,
            headerName:
              users.value.find((item) => item.id == ruleForm.headerId)
                ?.nickname || '',
          },
          topicIds: topicData.map((item) => item.id),
        }
        projectPlanUpdate(params)
          .then((res) => {
            if (res.code == 0 || res.code == 200) {
              $baseMessage('修改成功')
              closeTabNavigate()
            }
          })
          .finally(() => {
            loading.value = false
          })
      }
    })
  }

  getUserList()
  getProjectTypes()
  getProjectInfo()
</script>

<style lang="scss" scoped>
  .plan-upload-container-padding {
    padding-bottom: 80px !important;

    .flex {
      display: flex;
      width: 100%;
    }
  }
</style>
